<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="update-password-head">
    <CommonHead title="修改用户密码"/>
  </header>

  <!--体: 修改密码表单-->
  <section class="update-password-body">

    <van-divider dashed>修改密码</van-divider>

    <!--表单: 提交表单时触发-->
    <van-form @submit="updatePassword">

      <!--单元格: 卡片风格-->
      <van-cell-group inset>

        <!--单元格项: 双绑对应的表单数据，双绑对应的表单校验规则，背景提示字，右侧图标，可清除，不提示-->
        <van-field v-model="formData['oldPassword']" :rules="formRule['oldPassword']" type="password"
                   placeholder="请输入原密码" right-icon="shield-o" clearable autocomplete="off"/>

        <van-field v-model="formData['newPassword']" :rules="formRule['newPassword']" type="password"
                   placeholder="请输入新密码" right-icon="shield-o" clearable autocomplete="off"/>

        <van-field v-model="formData['confirm']" :rules="formRule['confirm']" type="password"
                   placeholder="请再次输入密码" right-icon="shield-o" clearable autocomplete="off"/>

      </van-cell-group>

      <!--分割线-->
      <van-divider dashed></van-divider>

      <!--操作区: 确认修改按钮-->
      <article class="operation">
        <!--提交按钮: 圆角，区块，主要蓝，提交功能-->
        <van-button round block type="primary" native-type="submit">确认修改</van-button>
      </article>

    </van-form>

  </section>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {UPDATE_PASSWORD} from '@/api/user';
import {useStore} from "vuex";
import router from "@/router";
import {onBeforeMount, reactive, shallowReactive} from "vue";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();

// data: 用户主键
const userId = sessionStorage.getItem('userId');

// data: 表单数据对象
let formData = shallowReactive({'oldPassword': '', 'newPassword': '', 'confirm': ''});

// data: 表单校验规则
let formRule = reactive({
  'oldPassword': [
    {required: true, message: '原密码不能为空'},
    {pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '密码长度在4-16个字符'}
  ],
  'newPassword': [
    {required: true, message: '新密码不能为空'},
    {pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '密码长度在4-16个字符'}
  ],
  'confirm': [
    {required: true, message: '确认密码不能为空'},
    {validator: (value) => value === formData['newPassword'], message: '两次密码不一致'}
  ]
});

/* ==================== method ==================== */

// method: 修改用户密码
async function updatePassword() {

  // 异步修改用户密码
  let result = await UPDATE_PASSWORD(formData);
  let resp = result['data'];
  if (resp.code === SUCCESS) {

    // 修改登录状态
    await vuex.dispatch('setLoginFlag', false);

    // 清除sessionStorage中的token值
    sessionStorage.removeItem("token");

    // 清除sessionStorage中的userId值
    sessionStorage.removeItem("userId");

    // 成功提示
    showSuccessToast("修改成功");

    // 跳转到LoginByAccount组件重新登录
    await router.push("/LoginByAccount");

  } else {
    showFailToast(resp.message + ': ' + resp.data);
  }
}

/* ==================== beforeMount ==================== */

// beforeMount: DOM挂载前，判断用户是否登录
onBeforeMount(() => {
  if (!vuex.state['loginFlag']) {
    showFailToast('请先登录');
    setTimeout(() => router.push("/LoginByAccount"), 1000);
  }
});

</script>

<style scoped lang="scss">
.operation {
  padding: 0 15px;
}
</style>